package cn.xz.xy.activity

import android.os.Handler
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.xz.xy.R
import cn.xz.xy.adapter.DeviceCAdapter
import cn.xz.xy.adapter.DeviceTAdapter
import cn.xz.xy.base.BaseActivity
import cn.xz.xy.base.BaseApplication
import cn.xz.xy.bean.AreaList
import cn.xz.xy.bean.CommonLib
import cn.xz.xy.bean.DeviceList
import cn.xz.xy.databinding.ActivityDeviceBinding
import cn.xz.xy.dialog.AllClickDialog
import cn.xz.xy.dialog.DeviceClickDialog
import cn.xz.xy.net.ControlDevice
import cn.xz.xy.util.*

/**
 * 设备管理界面
 * */
class DeviceActivity : BaseActivity<ActivityDeviceBinding>(R.layout.activity_device) {

    //内容集合
    private val mCList: MutableList<DeviceList> = arrayListOf()
    //默认所有ID
    private val mID = -999
    //一页显示多少个数据(只能是偶数，否则界面不能平均分)
    private var mNum = 8
    //分组用的集合
    private val myFList: MutableList<DeviceList> = arrayListOf()
    //列表集合
    private val mList: MutableList<RecyclerView> = arrayListOf()
    //适配器集合
    private val mAdapterList: MutableList<DeviceCAdapter> = arrayListOf()
    //用来存放圆点
    var tipList: Array<TextView?> = arrayOfNulls<TextView>(3)
    //获取设备状态
    private var handler: Handler? = null
    //当前显示界面的适配器
    private var mAdapter: DeviceCAdapter? = null
    //当前查询设备的下标
    private var queryIndex: Int = 0
    //类型
    private var lTag = 0

    override fun initData() {
        lTag = intent.getIntExtra(CommonLib.JUMP_TYPE,0);
        //获取内容
        //设备
        val mD = SessionUtils.getDataList(CommonLib.Device_CACHE, DeviceList::class.java)
        val deviceList: ArrayList<DeviceList> = arrayListOf()
        if (lTag == 0){
            //上合
            mD.forEach {
                if (it.areaName.contains("上合")){
                    deviceList.add(it)
                }
            }
        }else{
            //其他
            mD.forEach {
                if (!it.areaName.contains("上合")){
                    deviceList.add(it)
                }
            }
        }
        //设置内容，有内容再去设置标题
        if (deviceList.isNotEmpty()){
            //获取标题
            val hallList = SessionUtils.getDataList(CommonLib.Hall_CACHE, AreaList::class.java)
            //设置标题
            if (hallList.isNotEmpty() && hallList.size > 1){
                mDataBind.rvDeviceTitle.visible()
                //默认添加一个所有
                hallList.add(0,AreaList(mID,"所有设备", select = true))
                setHall(hallList)
            }else{
                mDataBind.rvDeviceTitle.invisible()
            }

            mCList.clear()
            mCList.addAll(deviceList)
            createDevice(mCList)
        }
    }

    override fun initEvent() {
        //一键全开
        mDataBind.tvOpenAll.setOnClickListener {
            AllClickDialog.newInstance(true,object : AllClickDialog.OnClickListener{
                override fun onYes() {
                    //全开全关的时候不进行状态查询，等全开完或者关完再说
                    handler?.removeCallbacks(getStatusAll)
                    ControlDevice.openAllDevice(lTag,object :ControlDevice.OpenDeviceListener{
                        override fun over() {
                            queryIndex = 0
                            //实时获取设备状态
                            handler?.post(getStatusAll)
                        }
                    })
                }
                override fun onNo() {
                }
            }).show(this.supportFragmentManager,"AllClickDialog1")
        }
        //一键全关
        mDataBind.tvCloseAll.setOnClickListener {
            AllClickDialog.newInstance(false,object : AllClickDialog.OnClickListener{
                override fun onYes() {
                    //全开全关的时候不进行状态查询，等全开完或者关完再说
                    handler?.removeCallbacks(getStatusAll)
                    ControlDevice.closeAllDevice(lTag,object :ControlDevice.CloseDeviceListener{
                        override fun over() {
                            queryIndex = 0
                            //实时获取设备状态
                            handler?.post(getStatusAll)
                        }
                    })
                }
                override fun onNo() {
                }
            }).show(this.supportFragmentManager,"AllClickDialog2")
        }
        //返回
        mDataBind.tvBack.setOnClickListener {
            finish()
        }
    }

    private fun setHall(l: MutableList<AreaList>){
        val ms = LinearLayoutManager(this)
        ms.orientation = LinearLayoutManager.HORIZONTAL // 设置 recyclerview 布局方式为横向布局
        val mAdapter = DeviceTAdapter()
        mDataBind.rvDeviceTitle.layoutManager = ms
        mDataBind.rvDeviceTitle.adapter = mAdapter
        mAdapter.setList(l)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            //更改选中状态
            val mT = adapter.data as MutableList<AreaList>
            mT.forEach {
                it.select = false
            }
            mT[position].select = true
            adapter.notifyDataSetChanged()
            //重置对应数据
            val mData = mT[position]
            if (mData.id == mID){
                createDevice(mCList)
            }else{
                val mNewList: MutableList<DeviceList> = arrayListOf()
                mCList.forEach {
                    if (it.areaID == mData.id){
                        mNewList.add(it)
                    }
                }
                createDevice(mNewList)
            }
        }
    }

    private fun createDevice(l: MutableList<DeviceList>){
        mList.clear()
        mAdapterList.clear()
        //创建分组数据
        for (i in 0 until l.size){
            //循环添加数据
            myFList.add(l[i])
            if (myFList.size == mNum){
                //到达规定数量创建一个列表
                createRecycler(myFList)
                myFList.clear()
            }
        }
        //最后的数据也要作为一个界面
        if (myFList.size > 0) {
            createRecycler(myFList)
        }
        myFList.clear()
        //ViewPager相关
        initViewPage()
    }

    private fun initViewPage() {
        mDataBind.vpList.adapter = MyPagerAdapter(mList)
        mDataBind.vpList.currentItem = 0
        mDataBind.vpList.offscreenPageLimit = 2
        //每次清一下监听，否则会重复监听
        mDataBind.vpList.clearOnPageChangeListeners()
        mDataBind.vpList.addOnPageChangeListener(object :
            ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                setFirst(position)
                //切换时改变小圆点
                selectTitle(position)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

        //设置小圆点
        setTitle()
        if (handler == null){
            handler = Handler()
        }
        setFirst(0)
    }

    //消息重置操作
    private fun setFirst(i: Int){
        if (handler != null && mAdapterList.isNotEmpty()){
            //默认当前界面适配器为第一个
            mAdapter = mAdapterList[i]
            //重置
            queryIndex = 0
            handler?.removeCallbacks(getStatusAll)
            //实时获取设备状态
            handler?.post(getStatusAll)
        }
    }

    private fun createRecycler(l: MutableList<DeviceList>){
        val mRecyclerView = RecyclerView(this)
        val layoutParams = RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.MATCH_PARENT
        )
        mRecyclerView.layoutParams = layoutParams


        val ms = object : GridLayoutManager(this, mNum/2) {
            //禁止上下滑动
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerView.layoutManager = ms

        val mAdapter = DeviceCAdapter()
        //暂存到集合里面统一处理
        mAdapterList.add(mAdapter)
        mRecyclerView.adapter = mAdapter
        mAdapter.setList(l)
        //设备点击事件
        mAdapter.setOnItemClickListener { adapter, view, position ->
            setAdapter(adapter as DeviceCAdapter ,position)
        }
        mList.add(mRecyclerView)
    }

    //适配器统一处理
    private fun setAdapter(adapter: DeviceCAdapter, position: Int){
        for (a in mAdapterList) {
            if (a == adapter) { //选中的
                handler?.removeCallbacks(getStatusAll)
                //弹窗开的时候不进行状态查询，等关闭了再说
                val data: MutableList<DeviceList> = a.data
                DeviceClickDialog.newInstance(
                    data[position],
                    object :DeviceClickDialog.OnClickListener{
                        override fun onDis() {
                            handler?.post(getStatusAll)
                        }

                    }
                ).show(this.supportFragmentManager,"DeviceClickDialog")
            }
        }
    }

    //ViewPager适配器
    internal class MyPagerAdapter(private val list: MutableList<RecyclerView>) :
        PagerAdapter() {
        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            if (position < list.size){
                container.removeView(list[position])
            }
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(list[position])
            return list[position]
        }

        override fun getCount(): Int {
            return list.size
        }

        override fun isViewFromObject(view: View, ob: Any): Boolean {
            return ob === view
        }
    }

    /**
     * 切换小圆点*/
    private fun selectTitle(p: Int){
        mDataBind.llIndex.removeAllViews()
        for (i in tipList.indices) {
            if (i == p) {
                tipList[i]!!.background =
                    ContextCompat.getDrawable(BaseApplication.getContext(),R.mipmap.icon_s1)
            } else {
                tipList[i]!!.background =
                    ContextCompat.getDrawable(BaseApplication.getContext(),R.mipmap.icon_s2)
            }
            mDataBind.llIndex.addView(tipList[i])
        }
    }

    /**
     * 设置小圆点
     * */
    private fun setTitle() {
        mDataBind.llIndex.removeAllViews()
        tipList = arrayOfNulls(mList.size)
        if (tipList.size > 1) {
            for (i in tipList.indices) {
                val textView = TextView(this)

                val lp = RelativeLayout.LayoutParams(AppHelper.dp2px(16f), AppHelper.dp2px(8f))
                lp.setMargins(0, 0, AppHelper.dp2px(7f), 0)
                textView.layoutParams = lp

                tipList[i] = textView
                //默认第一张图显示为选中状态
                if (i == 0) {
                    tipList[i]!!.background = ContextCompat.getDrawable(BaseApplication.getContext(), R.mipmap.icon_s1)
                } else {
                    tipList[i]!!.background = ContextCompat.getDrawable(BaseApplication.getContext(), R.mipmap.icon_s2)
                }
                mDataBind.llIndex.addView(tipList[i])
            }
        }
    }

    private var getStatusAll: Runnable = object : Runnable {
        override fun run() {
            //当前显示的适配器的数据
            if (mAdapter != null){
                val mGetData = mAdapter?.data!!
                if (mGetData.size > 0) {
                    //获取数据
                    val setTcpData = mGetData[queryIndex]
                    //测试地址
                    //MoveViewUtils.setTestLocationData(setTcpData)
                    //发送数据
                    SendTcpUtils.sendDevice(setTcpData,queryIndex,object :SendTcpUtils.OnDeviceListener{
                            override fun get(b: Boolean,index: Int) {
                                setDeviceStatus(b,index)
                            }
                        })
                    //平时800毫秒一次
                    handler?.postDelayed(this, 800)
                    queryIndex++
                    //到达固定长度之后五秒重发
                    if (queryIndex == mGetData.size) {
                        handler?.removeCallbacks(this)
                        queryIndex = 0
                        handler?.postDelayed(this, 5000)
                    }
                } else {
                    handler?.removeCallbacks(this)
                    queryIndex = 0
                }
            }
        }
    }

    //动态更换设备状态
    private fun setDeviceStatus(b: Boolean,position: Int){
        if (mAdapter != null){
            try {
                val mBean = mAdapter!!.data
                //根据下标去判断当前条目状态是否改变，改变了才更新状态
                if (mBean[position].opening != b){
                    mBean[position].opening = b
                    runOnUiThread {
                        mAdapter!!.notifyItemChanged(position)
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
                runOnUiThread {
                    mAdapter!!.notifyDataSetChanged()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //及时置空
        if (handler != null){
            handler?.removeCallbacks(getStatusAll)
            handler = null
        }
    }

}